package cn.com.pc.content.util;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ElasticUtil {
    private ElasticUtil(){}

    public static Class<?> getClazz(String clazzName){
        try {
            return Class.forName(clazzName);
        }catch (ClassNotFoundException e){
            log.error("getClazz: "+e.getMessage());
            return null;
        }
    }

    /**
     * 构建SearchSourceBuilder对象
     * @param queryBuilder 设置查询对象
     * @param from 设置from选项，确定要开始搜索的结果索引，默认为0
     * @param size 设置大小选项，确定要返回的搜索匹配数，默认为10
     * @param timeout 设置超时时间
     * @return org.elasticsearch.search.builder.SearchSourceBuilder
     * */
    public static SearchSourceBuilder initSearchSourceBuilder(QueryBuilder queryBuilder, int from, int size, int timeout, boolean trackTotalHits){
        //使用默认选项创建 SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置查询对象，可以使用任何类型的 QueryBuilder
        sourceBuilder.query(queryBuilder);
        //设置from选项，确定要开始搜索的结果索引，默认为0
        sourceBuilder.from(from);
        //设置大小选项，确定要返回的搜索匹配数，默认为10
        sourceBuilder.size(size);
        //设置是否查询所有，默认查10000条
        if (trackTotalHits) {
            sourceBuilder.trackTotalHits(trackTotalHits);
        }
        sourceBuilder.timeout(new TimeValue(timeout, TimeUnit.SECONDS));
        return sourceBuilder;

    }

    /**
     * 构建SearchSourceBuilder对象
     * @param queryBuilder 设置查询对象
     * @param sortBuilder 设置排序对象
     * @param from 设置from选项，确定要开始搜索的结果索引，默认为0
     * @param size 设置大小选项，确定要返回的搜索匹配数，默认为10
     * @param timeout 设置超时时间
     * @return org.elasticsearch.search.builder.SearchSourceBuilder
     * */
    public static SearchSourceBuilder initSearchSourceBuilder(QueryBuilder queryBuilder, SortBuilder<?> sortBuilder, int from, int size, int timeout, boolean trackTotalHits){
        //使用默认选项创建 SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置查询对象，可以使用任何类型的 QueryBuilder
        sourceBuilder.query(queryBuilder);
        //设置排序对象
        sourceBuilder.sort(sortBuilder);
        //设置from选项，确定要开始搜索的结果索引，默认为0
        sourceBuilder.from(from);
        //设置大小选项，确定要返回的搜索匹配数，默认为10
        sourceBuilder.size(size);
        //设置是否查询所有，默认查10000条
        sourceBuilder.trackTotalHits(trackTotalHits);
        sourceBuilder.timeout(new TimeValue(timeout, TimeUnit.SECONDS));
        return sourceBuilder;

    }

    public static SearchSourceBuilder initSearchSourceBuilder(QueryBuilder queryBuilder){
        return initSearchSourceBuilder(queryBuilder, 0, 10, 60, false);
    }
}
